// 从插件实现文件导入
export * from './vite-plugin-nacos';
export * from './utils';
import { nacosServiceManage } from './nacosServiceManage';
import { mergeConfig } from 'vite';

export const init = async (env: Record<string, string>) => {
    const serverList = env.VITE_NACOS_ADDRESS;
    const serviceName = env.VITE_SERVER_NAME;
    const port = Number(env.VITE_SERVER_PORT);

    if (!serverList || !serviceName || Number.isNaN(port)) {
        throw new Error('[vite-plugin-nacos] 缺少必要环境变量：VITE_NACOS_ADDRESS / VITE_SERVER_NAME / VITE_SERVER_PORT');
    }

    const nacos = await nacosServiceManage.create({
        serverList,
        serviceName,
        port
    });

    const isMain = serviceName === 'main-app';

    if (isMain) {
        console.log('[vite-plugin-nacos] 不需要服务发现，进行配置发现...');

        // 并发获取配置并稳健解析
        const [baseUrlRaw, httpTimeOut] = await Promise.all([
            nacos.getConfig('baseUrl', 'DEFAULT_GROUP'),
            nacos.getConfig('httpTimeOut', 'DEFAULT_GROUP')
        ]);

        let baseUrlConfig: Record<string, any> = {};
        if (baseUrlRaw) {
            try {
                baseUrlConfig = JSON.parse(baseUrlRaw);
            } catch (e) {
                console.warn('[vite-plugin-nacos] baseUrl 配置不是有效 JSON，忽略解析，使用空对象');
                baseUrlConfig = {};
            }
        }
        if (typeof httpTimeOut !== 'undefined' && httpTimeOut !== null) {
            baseUrlConfig.httpTimeOut = httpTimeOut;
        }

        // 将新配置处理成 define，需要 JSON.stringify
        const customizeEnv = Object.keys(baseUrlConfig).reduce<Record<string, string>>((acc, key) => {
            acc[`import.meta.env.VITE_${key.toUpperCase()}`] = JSON.stringify(baseUrlConfig[key]);
            return acc;
        }, {});

        // 将现有 env 处理成 define，需要 JSON.stringify
        const existingDefine = Object.keys(env).reduce<Record<string, string>>((acc, key) => {
            acc[`import.meta.env.${key}`] = JSON.stringify(env[key]);
            return acc;
        }, {});

        // 使用 mergeConfig 合并 define 字段
        const merged = mergeConfig({ define: existingDefine }, { define: customizeEnv });

        await closeAllNacos(serviceName);
        return merged;
    }

    // 非主模块：进行服务发现
    console.log('[vite-plugin-nacos] 进行 配置发现，获取依赖模块的地址...');
    const modelNames: string[] = [];
    for (const key in env) {
        if (key.includes('VITE_MODEL_') && env[key]) {
            modelNames.push(env[key]);
        }
    }

    // 去重
    const uniqueModelNames = Array.from(new Set(modelNames));
    const modelUrl: Record<string, string> = {};


    if (uniqueModelNames.length > 0) {
        const results = await Promise.all(uniqueModelNames.map(async (val) => {
            const url = await nacos.getConfig(val, 'DEFAULT_GROUP');
            const envKey = `VITE_MODEL_${val.replace('app-', '').toUpperCase()}_URL`;
            return [envKey, url] as const;
        }));
        for (const [k, v] of results) modelUrl[k] = v;
    }

    console.log('[vite-plugin-nacos] modelUrl: ', modelUrl);
    await closeAllNacos("other-model");
    return modelUrl;
}

/** 手动关闭所有 Nacos 客户端（提供给外部在需要时调用） */
export async function closeAllNacos(serviceName: string) {
    await nacosServiceManage.destroyAll();
}
